<template>
	<view>
		<web-view :webview-styles="webviewStyles" :src="url"></web-view>
		<!-- index.wxml -->
		<!--    <scroll-view class="scrollarea" scroll-y type="list">
      <view class="container">
        <view>
          <text>当前连接设备:</text>
          <text>{{ connectedDeviceId }}</text>
        </view>
        <view>
          <text>连接状态:</text>
          <text>{{ connected ? '已连接' : '未连接' }}</text>
          <button @tap="closeDevice(connectedDeviceId)">断开连接</button>
        </view>
        <image src="https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AAOEcgc.img" mode="widthFix"></image>
        <view>
          <button @tap="onSendMessage">发送图片11</button>
          <button @tap="onResetFileTranse">复位远端</button>
          <button @tap="onWifiPostImage">wifi传图</button>
        </view>
        <view class="device-list">
          <block class="device" v-for="(item, index) in devices" :key="index">
            <view>
              <text>{{ item.name || '未知设备' }}</text>
              <text>{{ item.deviceId }}</text>
              <view>
                <button @tap="connectDevice(item.deviceId)">连接</button>
              </view>
            </view>
          </block>
        </view>
      </view>
    </scroll-view> -->
	</view>
</template>

<script>
	// index.js
	import DataChannel from '@/utils/BTSerial.js';
	export default {
		data() {
			return {
				url: "https://www.yingmiao.fun/api/web/video1",
				dataChannel: null,
				devices: [],

				// 存储已搜索到的蓝牙设备
				connected: false,

				// 标识蓝牙是否已连接
				connectedDeviceId: '',

				// 当前连接设备
				serviceId: '',

				// 蓝牙服务ID
				writeCharacteristicId: '',

				// 可写入的特征ID
				notifyCharacteristicId: '',

				sendProgress: ''
			};
		}, // 页面加载时打开蓝牙
		onLoad() {
			// 初始化 DataChannel 实例
			// this.dataChannel = new DataChannel(this.sendDataViaBluetooth)
			// this.openBluetooth();
			// uni.onBLECharacteristicValueChange((res) => {
			// 	//console.log("onBLECharacteristicValueChange:" + res);
			// 	//console.log(res.value);
			// 	this.dataChannel.onRecvData(res.value, (percent, offset, status) => {
			// 		console.log(`接收进度: ${percent}% 状态: ${status}`);
			// 	});
			// });
		},
		methods: {
			// 初始化蓝牙适配器
			openBluetooth() {
				uni.stopBluetoothDevicesDiscovery();
				uni.closeBluetoothAdapter();
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log('蓝牙适配器初始化成功', res);
						this.startBluetoothDevicesDiscovery();
					},
					fail: (err) => {
						console.error('蓝牙适配器初始化失败', err);
						uni.showToast({
							title: '请打开蓝牙',
							icon: 'none'
						});
					}
				});
			},

			// 搜索蓝牙设备
			startBluetoothDevicesDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						console.log('开始搜索蓝牙设备', res);
						this.onBluetoothDeviceFound();
					},
					fail: (err) => {
						console.error('搜索蓝牙设备失败', err);
					}
				});
			},

			// 监听蓝牙设备
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound((res) => {
					//console.log('发现新设备', res);
					let newDevices = res.devices || [];
					let existingDevices = this.devices;

					// 指定设备名称前缀
					//const prefix = "BLE_";
					const prefix = 'YM_';
					//const prefix = "D36";

					// 过滤出新设备中名称符合前缀且不存在于已知设备中的
					newDevices.forEach((device) => {
						if (device.name && device.name.startsWith(prefix)) {
							const isExisting = existingDevices.some((d) => d.deviceId === device.deviceId);
							if (!isExisting) {
								existingDevices.push(device);
							}
						}
					});
					this.devices = existingDevices
				});
			},

			// 连接蓝牙设备
			createBLEConnection(deviceId) {
				if (this.connectedDeviceId === deviceId) {
					uni.showToast({
						title: '设备已连接',
						icon: 'none'
					});
					return;
				}
				// 显示进度条
				uni.showLoading({
					title: '连接中...',
					mask: true
				});
				uni.createBLEConnection({
					deviceId,
					success: (res) => {
						console.log('蓝牙设备连接成功', res);
						this.connected = true
						this.connectedDeviceId = deviceId

						uni.showToast({
							title: '蓝牙设备已连接',
							icon: 'success'
						});

						// 连接成功后获取服务
						this.getBLEDeviceServices(deviceId);
					},
					fail: (err) => {
						console.error('连接蓝牙设备失败', err);
						uni.showToast({
							title: '连接失败',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},

			// 获取设备服务
			getBLEDeviceServices(deviceId) {
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						console.log('获取服务列表成功', res.services);
						const services = res.services;
						if (services.length > 0) {
							//遍历service,找到可以写入的特征列表
							for (var serviceItem of services) {
								const serviceId = serviceItem.uuid;
								this.getBLEDeviceCharacteristics(deviceId, serviceId);
							}
						}
					},
					fail: (err) => {
						console.error('获取服务列表失败', err);
					}
				});
			},

			onBLEWriteUUIDFinished() {
				console.log('开始监听读取消息:');
				uni.notifyBLECharacteristicValueChanged({
					state: true,
					// 启用 notify 功能
					deviceId: this.connectedDeviceId,
					serviceId: this.serviceId,
					characteristicId: this.notifyCharacteristicId,
					success: function(res) {
						console.error('启用接受消息成功');
					},
					fail: (err) => {
						console.error('启用接受消息失败', err);
						uni.showToast({
							title: '启用接受消息失败',
							icon: 'none'
						});
					}
				});
			},

			// 获取特征
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				if (serviceId !== '0000AE30-0000-1000-8000-00805F9B34FB') {
					return;
				}
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						console.log('获取特征列表成功 service:', serviceId);
						const characteristics = res.characteristics;

						// 找到支持写入（write）的特征
						const writeCharacteristic = characteristics.find((char) => char.properties.write);
						if (writeCharacteristic) {
							console.log('找到可写入特征:', writeCharacteristic.uuid);
							if (writeCharacteristic.uuid.startsWith('0000AE01')) {
								console.log('==>使用写入特征:', writeCharacteristic.uuid);
								this.writeCharacteristicId = writeCharacteristic.uuid
								this.serviceId = serviceId
								//this.onBLEWriteUUIDFinished();
							}
						}

						if (this.notifyCharacteristicId === '') {
							const notifyCharacteristic = characteristics.find((char) => char.properties
								.notify);
							if (notifyCharacteristic) {
								console.log('找到notify特征:', notifyCharacteristic.uuid);
								if (notifyCharacteristic.uuid.startsWith('0000AE02')) {
									console.log('==>使用notify特征:', notifyCharacteristic.uuid);
									this.notifyCharacteristicId = notifyCharacteristic.uuid
									this.onBLEWriteUUIDFinished();
								}
							}
						}
					},
					fail: (err) => {
						console.error('获取特征列表失败', err);
					}
				});
			},

			// 发送数据到蓝牙设备
			sendBLEMessage(message) {
				const {
					connectedDeviceId,
					serviceId,
					writeCharacteristicId
				} = this;
				if (!serviceId || !writeCharacteristicId) {
					uni.showToast({
						title: '未找到可写入特征',
						icon: 'none'
					});
					return;
				}

				// 将消息转换为 ArrayBuffer
				const buffer = new ArrayBuffer(message.length);
				const dataView = new DataView(buffer);
				for (let i = 0; i < message.length; i++) {
					dataView.setUint8(i, message.charCodeAt(i));
				}
				console.log('buffer byteLength', buffer.byteLength);
				uni.writeBLECharacteristicValue({
					deviceId: connectedDeviceId,
					serviceId,
					characteristicId: writeCharacteristicId,
					value: buffer,
					success: (res) => {
						console.log('消息发送成功', res);
						uni.showToast({
							title: '消息发送成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						console.error('消息发送失败', err);
						uni.showToast({
							title: '消息发送失败',
							icon: 'none'
						});
					}
				});
			},

			// 断开蓝牙设备连接
			closeBLEConnection(deviceId) {
				if (!this.connected) {
					return;
				}
				uni.closeBLEConnection({
					deviceId,
					success: (res) => {
						console.log('蓝牙设备断开成功', res);
						uni.showToast({
							title: '蓝牙设备断开成功',
							icon: 'none'
						});
						this.connected = true
						this.connectedDeviceId = ""
						this.serviceId = ""
						this.writeCharacteristicId = ""
					},
					fail: (err) => {
						console.error('断开蓝牙设备连接失败', err);
						uni.showToast({
							title: '断开蓝牙设备连接失败',
							icon: 'none'
						});
					}
				});
			},

			// 使用网络图片路径发送蓝牙数据
			sendNetworkImageBLEMessage(imageUrl) {
				if (!this.connected) {
					return;
				}
				uni.downloadFile({
					url: imageUrl,
					success: (res) => {
						const filePath = res.tempFilePath;
						uni.getFileSystemManager().readFile({
							filePath: filePath,
							success: (readRes) => {
								uni.showToast({
									title: '读取图片成功，开始发送数据',
									icon: 'none'
								});
								const buffer = readRes.data; // ArrayBuffer 格式
								this.sendBinaryFile(buffer); // 调用发送函数
							},

							fail: (err) => {
								console.error('读取图片失败', err);
								uni.showToast({
									title: '读取图片失败',
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('下载图片失败', err);
						uni.showToast({
							title: '读取图片失败',
							icon: 'none'
						});
					}
				});
			},

			sendDataViaBluetooth(data) {
				const buffer = new Uint8Array(data).buffer;

				// console.log("-->serviceId:", this.data.serviceId, " writeCharacteristicId:", this.data.writeCharacteristicId);
				uni.writeBLECharacteristicValue({
					deviceId: this.connectedDeviceId,
					serviceId: this.serviceId,
					characteristicId: this.writeCharacteristicId,
					value: buffer,
					success: (res) => {
						// console.log("蓝牙数据发送成功", res);
					},
					fail: (err) => {
						console.error('蓝牙数据发送失败', err);
					}
				});
			},

			sendBinaryFile(fileData) {
				const format = 'jpg'; // 假设发送的是jpg格式
				try {
					this.dataChannel.sendBinaryFile(fileData, format, (percent, offset, status) => {
						// 更新进度
						this.sendProgress = percent

						console.log(`文件发送进度: ${percent}% 已发送: ${offset} 状态: ${status}`);
						// 根据状态处理文件发送的不同阶段
						if (status === 'success') {
							console.log('文件发送成功');
							uni.showToast({
								title: '图片发送成功',
								icon: 'success'
							});
						} else if (status === 'start') {
							console.log('文件发送开始');
						} else if (status === 'sending') {
							//console.log(`文件发送中... ${percent}% 完成`);
						} else {
							console.error('文件发送失败: ', status);
						}
					});
				} catch (error) {
					console.log('CatchClause', error);
					console.log('CatchClause', error);
					console.error(error);
				}
			},

			// 点击某个设备进行连接
			connectDevice(deviceId) {
				this.createBLEConnection(deviceId);
			},

			// 点击某个设备断开连接
			closeDevice(deviceId) {
				this.closeBLEConnection(deviceId);
			},

			// 点击发送消息
			onSendMessage() {
				this.sendNetworkImageBLEMessage('https://xs.ttxcx.net/assets/addons/wanlshop/img/fish/testjpg.jpg');
			},

			onWifiPostImage() {
				uni.request({
					url: 'https://www.zerowait.cn/wserver/v1/api/playimg',
					// 你的API接口地址
					method: 'POST',
					// 请求方法
					data: {
						devid: '123456789',
						// 请求的参数
						url: 'http://47.108.175.141:18080/v1/files/img/liudehua.jpg'
					},
					header: {
						'content-type': 'application/json' // 设置请求的 content-type
					},

					success: function(res) {
						console.log(res.data); // 输出服务器返回的数据
					},

					fail: function(error) {
						console.error(error); // 输出错误信息
					}
				});
			},

			onResetFileTranse() {
				if (!this.connected) {
					return;
				}
				this.dataChannel.resetFileTransfer((percent, offset, status) => {
					console.log(`重置进度: ${percent}% 状态: ${status}`);
				});
			}
		}
	};
</script>
<style>
	/**index.wxss**/
	page {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.scrollarea {
		flex: 1;
		overflow-y: hidden;
	}

	.userinfo {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #aaa;
		width: 80%;
	}

	.userinfo-avatar {
		overflow: hidden;
		width: 128rpx;
		height: 128rpx;
		margin: 20rpx;
		border-radius: 50%;
	}

	.usermotto {
		margin-top: 200px;
	}

	.avatar-wrapper {
		padding: 0;
		width: 56px !important;
		border-radius: 8px;
		margin-top: 40px;
		margin-bottom: 40px;
	}

	.avatar {
		display: block;
		width: 56px;
		height: 56px;
	}

	.nickname-wrapper {
		display: flex;
		width: 100%;
		padding: 16px;
		box-sizing: border-box;
		border-top: 0.5px solid rgba(0, 0, 0, 0.1);
		border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
		color: black;
	}

	.nickname-label {
		width: 105px;
	}

	.nickname-input {
		flex: 1;
	}

	.device {
		border-top: 0.5px solid rgba(0, 0, 0, 0.1);
		border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
		margin-bottom: 10px;
	}
</style>